package com.zkingsoft.laqeelin.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.matrix.core.constance.MatrixConstance;
import com.matrix.core.constance.SystemErrorCode;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.PaginationVO;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.ModelUtils;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.tools.WebUtil;
import com.zkingsoft.common.bean.SysUsers;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.common.constance.AppMessageCode;
import com.zkingsoft.laqeelin.bean.BizHelp;
import com.zkingsoft.laqeelin.bean.BizHelpActivity;
import com.zkingsoft.laqeelin.bean.BizOrder;
import com.zkingsoft.laqeelin.bean.BizShare;
import com.zkingsoft.laqeelin.bean.BizUser;
import com.zkingsoft.laqeelin.bean.WxTemplateDate;
import com.zkingsoft.laqeelin.dao.BizHelpActivityDao;
import com.zkingsoft.laqeelin.dao.BizHelpDao;
import com.zkingsoft.laqeelin.dao.BizOrderDao;
import com.zkingsoft.laqeelin.dao.BizShareDao;
import com.zkingsoft.laqeelin.service.BizHelpService;
import com.zkingsoft.laqeelin.service.WxMsgTemplateService;
import com.zkingsoft.tools.Constants;
import com.zkingsoft.tools.WxUtils;

/**
 * @description service接口实现类(助力表)
 * @author 何明
 * @date 2018-09-01 10:35
 */
@Service
public class  BizHelpServiceImpl implements  BizHelpService{

	
	@Autowired
	private BizHelpDao bizHelpDao;

	@Autowired
	private BizShareDao bizShareDao;
	@Autowired
	private BizHelpActivityDao bizHelpActivityDao;

	@Autowired
	private BizOrderDao bizOrderDao;
	
	@Autowired
	private WxMsgTemplateService temService;
	@Override
	public int add(BizHelp bizHelp){
		// 设置基本字段信息
		SysUsers loginUser = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
		bizHelp.setCreateBy(loginUser.getSuName());
		bizHelp.setUpdateBy(loginUser.getSuName());
		bizHelp.setHelpId(UUIDUtil.getRandomID());
		return bizHelpDao.insert(bizHelp);
		
	}
	
	@Override
	public int batchAdd(List<BizHelp>  bizHelpList) {
		//这里没有做基本字段的设置，如有需要请自己实现	
		int num = 0;
		int c = 10000;
		int size = bizHelpList.size()/c + 1;
		for(int i=0; i<size; i++) {
			int begin = i*c;
			int end = (i+1)*c;
			end = end >= bizHelpList.size() ? bizHelpList.size() : end;
			List<BizHelp> insertList = bizHelpList.subList(begin, end);
			num += bizHelpDao.batchInsert(insertList);
		}
		return num;
		
	}
	
	
   	
    @Override
	public int modifyByMap(BizHelp oldBizHelp
	,BizHelp newBizHelp){
	
		Map<String, Object> modifyMap = null;
		try {
			if (!ModelUtils.isModified(oldBizHelp, newBizHelp)) {
				return MatrixConstance.DML_SUCCESSS;
			}
			modifyMap = ModelUtils.comparePojo2Map(oldBizHelp, newBizHelp);
		} catch (Exception e) {
			throw new GlobleException(SystemErrorCode.DATA_UPDATE_FAIL, e, newBizHelp);
		}
		if (modifyMap.size() > 0) {
			modifyMap.put("helpId", oldBizHelp.getHelpId());
			bizHelpDao.updateByMap(modifyMap);
		}
		return MatrixConstance.DML_SUCCESSS;
	}
	
	@Override
	public int modifyByModel(BizHelp bizHelp){
	
		return bizHelpDao.updateByModel(bizHelp);
	
	}
	
	
	
	@Override
	public int remove(List<String> list){
	
		return bizHelpDao.deleteByIds(list);
	
	}

	@Override
	public int removeById(String helpId){
	
		return bizHelpDao.deleteById(helpId);
	
	}
	
	@Override
	public int removeByModel(BizHelp bizHelp){
	
		return bizHelpDao.deleteByModel(bizHelp);
	
	}
	
	
	@Override
	public List<BizHelp> findInPage(BizHelp bizHelp,  PaginationVO pageVo){
	
		return bizHelpDao.selectInPage(bizHelp , pageVo);
	
	}
	
	@Override
	public List<BizHelp> findByModel(BizHelp bizHelp){
	
		return bizHelpDao.selectByModel(bizHelp);
	
	}
	
	@Override
	public int  findTotal(BizHelp bizHelp){
	
		return bizHelpDao.selectTotalRecord(bizHelp);
	
	}
	
	@Override
	public BizHelp  findById(String helpId){
	
		return bizHelpDao.selectById(helpId);
	
	}

	@Override
	public int addHelp(BizHelp bizHelp,BizShare bizShare,String formId) {
		//如果助力人数达到上限，则修改分享状态，生成订单信息
		int needNum=bizShare.getActivity().getHacNum();
		BizHelpActivity bizHelpActivity=bizHelpActivityDao.selectByActId(bizShare.getProId());
		String actId=bizHelpActivity.getActId()+"";
		String openId=bizShare.getUserId();
	
//		String sharePrizeTime=bizShare.getActivity().getBizSharePrize().getPrizeTime();
//		String helpPrizeTime=bizShare.getActivity().getBizHelpPrize().getPrizeTime();
		int hasNum=bizShare.getHelps().size();
			hasNum+=1;
			if(hasNum>=needNum){
				//修改分享状态为已完成
				BizShare share=new BizShare();
				share.setShaId(bizShare.getShaId());
				share.setShaStatus(AppConstance.SHARE_STATUS_YWC);
				bizShareDao.updateByModel(share);
				//发送模板消息--分享人
				if(StringUtils.isNotBlank(bizShare.getShaRemark())){
					WxTemplateDate date=new WxTemplateDate();
					LogUtil.debug("助力完成发送模板消息：{}", openId);
					date.setUrl("pages/active/active?id="+actId+"&openId="+openId);
					date.setFirstKeywordValue(bizHelpActivity.getHacName());
					date.setOpenId(bizShare.getUserId());
					date.setTemplateId(Constants.HELP_TEMPLATE_ID);
					date.setFormId(bizShare.getShaRemark());
					date.setSecondKeywordValue(bizHelpActivity.getBizSharePrize().getPrizeName());
					date.setThreeKeywordValue("您的好友 "+bizHelp.getNickName()+" 为你助力成功,请点击查看");
					temService.xcxTemMsg(date);
				}
				
			}
		int i=bizHelpDao.insert(bizHelp);
		return i;
	}

	@Override
	public BizOrder receiveSharePrize(BizUser loginUser,BizOrder order) {
		BizShare bizShare=bizShareDao.selectByIdAndOpenId(loginUser.getOpenId(),order.getShareId());
		if(bizShare==null){
			throw new GlobleException(AppMessageCode.HelpAct.INFO_ERR);
		}
		if(bizShare.getShaStatus()!=AppConstance.SHARE_STATUS_YWC){
			throw new GlobleException(AppMessageCode.HelpAct.REC_ERR_SHARE);
		}
		//生成分享订单
		order.setCreateBy(loginUser.getOpenId());
		order.setUpdateBy(loginUser.getOpenId());
		order.setHacId(bizShare.getProId());
		order.setOrderId(UUIDUtil.getRandomID());
		order.setOrderType(AppConstance.ORDER_TYPE_FX);//分享
		order.setShareId(bizShare.getShaId());
		order.setUserId(loginUser.getOpenId());
		//检查消费码是否唯一
		String code="";
		int num=0;
		do{
			code=WxUtils.getRandomNum(8);
			num=bizOrderDao.selectCodeTotal(code);
		}while(num>0);
		order.setOrderCode(code);
		order.setOrderStatus(AppConstance.ORDER_STATUS_YLQ);
		BizHelpActivity bizHelpActivity=bizHelpActivityDao.selectByActId(bizShare.getProId());
		if(bizHelpActivity.getHacStatus()!=AppConstance.ACT_STATUS_FB 
				|| (bizHelpActivity.getHacEndTime()!=null && new Date().getTime()>bizHelpActivity.getHacEndTime().getTime())){
			throw new GlobleException(AppMessageCode.HelpAct.ACT_LOSE);
		}
		order.setPrizeName(bizHelpActivity.getBizSharePrize().getPrizeName());
		order.setPrizePrice(bizHelpActivity.getBizSharePrize().getPrizePrice());
		if(StringUtils.isNotBlank(bizHelpActivity.getBizSharePrize().getPrizeTime())){
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); 
			 Date date=null;
			try {
				date = format.parse(bizHelpActivity.getBizSharePrize().getPrizeTime());
				order.setUseTime(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		int i=bizOrderDao.insert(order);
		
		if(i>0){
			String actId=bizHelpActivity.getActId()+"";
			String openId=bizShare.getUserId();
			String sharePrizeTime=bizHelpActivity.getBizSharePrize().getPrizeTime();
			//修改分享状态为已完成
			BizShare share=new BizShare();
			share.setShaId(bizShare.getShaId());
			share.setShaStatus(AppConstance.SHARE_STATUS_YLQ);
			bizShareDao.updateByModel(share);
			//发送模板消息
			WxTemplateDate date=new WxTemplateDate();
			date.setUrl("pages/customerBenefit/benefit");
			date.setFirstKeywordValue(order.getPrizeName());
			date.setOpenId(order.getUserId());
			date.setFormId(order.getFormId());
			Date date1;
			try {
				date1 = new SimpleDateFormat("yyyy-MM-dd").parse(sharePrizeTime);
				sharePrizeTime = new SimpleDateFormat("yyyy年MM月dd日").format(date1);
			} catch (ParseException e) {
				LogUtil.error("时间格式化错误", e, "");
			}
			date.setSecondKeywordValue("即日起至"+sharePrizeTime);
			date.setThreeKeywordValue("领取成功，请尽快到店内消费");
			temService.xcxTemMsg(date);
		}
		
		

		BizOrder helporder=new BizOrder();
		//生成助力订单
		helporder.setCreateBy(loginUser.getOpenId());
		helporder.setUpdateBy(loginUser.getOpenId());
		helporder.setHacId(bizShare.getProId());
		helporder.setOrderId(UUIDUtil.getRandomID());
		helporder.setOrderType(AppConstance.ORDER_TYPE_FX);
		helporder.setShareId(bizShare.getShaId());
		helporder.setUserId(loginUser.getOpenId());
				//检查消费码是否唯一
				 code="";
				 num=0;
				do{
					code=WxUtils.getRandomNum(8);
					num=bizOrderDao.selectCodeTotal(code);
				}while(num>0);
				helporder.setOrderCode(code);
				helporder.setOrderStatus(AppConstance.ORDER_STATUS_YLQ);
				
				helporder.setPrizeName(bizHelpActivity.getBizHelpPrize().getPrizeName());
				helporder.setPrizePrice(bizHelpActivity.getBizHelpPrize().getPrizePrice());
				if(StringUtils.isNotBlank(bizHelpActivity.getBizHelpPrize().getPrizeTime())){
					SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); 
					 Date date=null;
					try {
						date = format.parse(bizHelpActivity.getBizHelpPrize().getPrizeTime());
						helporder.setUseTime(date);
					} catch (ParseException e) {
						LogUtil.error("时间格式化错误", e, "");
					}
				}
				
				bizOrderDao.insert(helporder);
		return order;
	}

	@Override
	public BizOrder receiveHelpPrize(String shareId,BizUser loginUser,String formId) {
		BizOrder order=new BizOrder();
		BizShare bizShare=bizShareDao.selectById(shareId);
		if(bizShare==null){
			throw new GlobleException(AppMessageCode.HelpAct.INFO_ERR);
		}
		//查询是否已助力
		BizHelp bizHelp=new BizHelp();
		bizHelp.setShareId(shareId);
		bizHelp.setUserId(loginUser.getOpenId());
		List<BizHelp> list=bizHelpDao.selectByModel(bizHelp);
		if(CollectionUtils.isEmpty(list)){
			throw new GlobleException(AppMessageCode.HelpAct.REC_ERR_HELP);
		}
		
		
		//生成助力订单
		order.setCreateBy(loginUser.getOpenId());
		order.setUpdateBy(loginUser.getOpenId());
		order.setHacId(bizShare.getProId());
		order.setOrderId(UUIDUtil.getRandomID());
		order.setOrderType(AppConstance.ORDER_TYPE_ZL);
		order.setShareId(bizShare.getShaId());
		order.setUserId(loginUser.getOpenId());
		//检查消费码是否唯一
		String code="";
		int num=0;
		do{
			code=WxUtils.getRandomNum(8);
			num=bizOrderDao.selectCodeTotal(code);
		}while(num>0);
		order.setOrderCode(code);
		order.setOrderStatus(AppConstance.ORDER_STATUS_YLQ);
		BizHelpActivity bizHelpActivity=bizHelpActivityDao.selectByActId(bizShare.getProId());
		if(bizHelpActivity.getHacStatus()!=AppConstance.ACT_STATUS_FB 
				|| (bizHelpActivity.getHacEndTime()!=null && new Date().getTime()>bizHelpActivity.getHacEndTime().getTime())){
			throw new GlobleException(AppMessageCode.HelpAct.ACT_LOSE);
		}
		order.setPrizeName(bizHelpActivity.getBizHelpPrize().getPrizeName());
		order.setPrizePrice(bizHelpActivity.getBizHelpPrize().getPrizePrice());
		if(StringUtils.isNotBlank(bizHelpActivity.getBizHelpPrize().getPrizeTime())){
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); 
			 Date date=null;
			try {
				date = format.parse(bizHelpActivity.getBizHelpPrize().getPrizeTime());
				order.setUseTime(date);
			} catch (ParseException e) {
				LogUtil.error("时间格式化错误", e, "");
			}
		}
		
		int i=bizOrderDao.insert(order);
		if(i>0){
			String actId=bizHelpActivity.getActId()+"";
			String openId=bizShare.getUserId();
			String helpPrizeTime=bizHelpActivity.getBizHelpPrize().getPrizeTime();
			//发送模板消息
			WxTemplateDate date=new WxTemplateDate();
			date.setUrl("pages/customerBenefit/benefit");
			date.setFirstKeywordValue(order.getPrizeName());
			date.setOpenId(order.getUserId());
			date.setTemplateId(Constants.PRIZE_TEMPLATE_ID);
			date.setFormId(formId);
			  Date date1;
			try {
				date1 = new SimpleDateFormat("yyyy-MM-dd").parse(helpPrizeTime);
				helpPrizeTime = new SimpleDateFormat("yyyy年MM月dd日").format(date1);
			} catch (ParseException e) {
				LogUtil.error("时间格式化错误", e, "");
			}
			date.setSecondKeywordValue("即日起至"+helpPrizeTime);
			date.setThreeKeywordValue("领取成功，请尽快到店内消费");
			temService.xcxTemMsg(date);
		}
		return order;
	}

   	
	
	
}